﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;
using Microsoft.WindowsAzure.Storage.DataMovement;

namespace WebAppLogAzureWebJobBackupRunner
{
    public class Functions
    {
        [FunctionName("TimerTriggerBackup")]
        public static void Run(
            [TimerTrigger("0 */0,2,4,6,8 * * * *")]TimerInfo myTimer, //DEBUG 两分钟一次
            TraceWriter log)
        {
            string webrootPath = Environment.GetEnvironmentVariable("WEBROOT_PATH");// "%WEBROOT_PATH%";
            DirectoryInfo dirInfo = new DirectoryInfo(
                Path.Combine(webrootPath, "logs"));

            if (myTimer.IsPastDue)
            {
                log.Info("Timer is running late!");
            }
            log.Info($"C# Timer trigger function executed webroot path {webrootPath} log path {(dirInfo.Exists ? dirInfo.FullName : string.Empty)} at: {DateTime.Now} {DateTime.UtcNow} ");

            if (dirInfo.Exists)
            {
                string pattern = "nlog-*.log";
                FileInfo[] infos = dirInfo.GetFiles(pattern);
                if (infos != null)
                {
                    string connectionStr = ConfigurationManager.ConnectionStrings["AzureWebAppLogOutputStorage"].ConnectionString;
                    string container = ConfigurationManager.AppSettings["AzureWebAppLogOutputContainer"];

                    var storageAccount = CloudStorageAccount.Parse(connectionStr);
                    CloudBlobClient client = storageAccount.CreateCloudBlobClient();
                    CloudBlobContainer blobcontainer = client.GetContainerReference(container);
                    var tempTask = blobcontainer.CreateIfNotExistsAsync();
                    tempTask.Wait();

                    foreach (var info in infos)
                    {
                        DateTime dt = DateTime.UtcNow;
                        string dtPattern = dt.ToString("yyyy-MM-dd");
                        if (!info.Name.Contains($"{dtPattern}.log"))
                        {
                            log.Info($"C# Timer search previous logfile: {(info.Exists ? info.FullName : string.Empty)}");

                            // When transfer large file to block blob, set TransferManager.Configurations.BlockSize to specify the size of the blocks.
                            // It must be between 4MB and 100MB and be multiple of 4MB. Default value is 4MB. 
                            //
                            // Currently, the max block count of a block blob is limited to 50000.
                            // When transfering a big file and the BlockSize provided is smaller than the minimum value - (size/50000),
                            // it'll be reset to a value which is greater than the minimum value and multiple of 4MB for this file.
                            TransferManager.Configurations.BlockSize = 4 * 1024 * 1024; //4MB

                            string sourceFileName = info.FullName;//"azure.png"; 
                            string destinationBlobName = info.Name;//"azure_blockblob.png"; 

                            // Create the destination CloudBlob instance 
                            CloudBlob destinationBlob = blobcontainer.GetBlockBlobReference(destinationBlobName);
                            //await Util.GetCloudBlobAsync(ContainerName, destinationBlobName, BlobType.BlockBlob);

                            // Use UploadOptions to set ContentType of destination CloudBlob
                            UploadOptions options = new UploadOptions();
                            SingleTransferContext context = new SingleTransferContext();
                            context.ShouldOverwriteCallbackAsync = async (object source, object destination) =>
                            {//overwrite exists blobs, return true
                                return true;
                            };
                            context.SetAttributesCallbackAsync = async (destination) =>
                            {//change blob content type, if don't, browser might download directly
                                CloudBlob destBlob = destination as CloudBlob;
                                //destBlob.Properties.ContentType = "text/plain"; 
                            };

                            // Start the upload 
                            var tempTask1 = TransferManager.UploadAsync(sourceFileName,
                                destinationBlob, options, context);
                            tempTask1.Wait();
                            if (!tempTask1.IsFaulted)
                            {
                                Console.WriteLine("File {0} is uploaded to {1} successfully.", sourceFileName, destinationBlob.Uri.ToString());
                                // at last, remove the source log file to reduce WebApp Disk usage. 
                                info.Delete();
                                Console.WriteLine("File {0} is deleted successfully.", sourceFileName);
                            }
                            else
                            {
                                Console.WriteLine("File {0} failed to upload to {1}.", sourceFileName, destinationBlob.Uri.ToString());
                            }
                        }
                        else
                        {
                            log.Info($"C# Timer search current logfile: {(info.Exists ? info.FullName : string.Empty)}");
                        }
                    }
                }
            }
        }
    }
}
